package _99练习;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

<<<<<<< HEAD
/**
 * @author ZhiCheng Qian
 * @since 2021/11/30 0:33
 */
=======

>>>>>>> 1c69d32fc055e0010098b09f71795769d9a12acd
public class synchronizedDemo3 implements Runnable {
	int count = 1000;

	Lock l = new ReentrantLock();

	@Override
	public void run() {
		while (count > 0) {
			// 尝试加锁
			if (l.tryLock()) {
				if (count > 0) {
					count--;
					System.out.println(Thread.currentThread().getName() + "吃一个包子，剩余" + count + "个");

				}
				// 解锁
				l.unlock();

			} else {
				System.out.println(Thread.currentThread().getName() + "这个包子别人在吃，不是你的！");
			}

			try {
				Thread.sleep(500);

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(Thread.currentThread().getName() + "吃完了");

	}
}
